/*
 * Copyright [2010] [GP Software]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gp.util;

import javax.swing.*;

/**
 * Utility class to launch a url to a web browser.
 * <p>
 * This is based on the code from Bare Bones Browser Launch
 * http://www.centerkey.com/java/browser/
 * </p>
 *
 * @author Dem Pilafian
 * @author Paul Augustine C. Mendoza
 */
public class BrowserLauncher {

    /** Supported browsers */
    private static final String[] SUPPORTED_BROWSERS = {"google-chrome", "firefox", "opera",
            "konqueror", "epiphany", "seamonkey", "galeon", "kazehakase", "mozilla"};


    /** Error message constant */
    private static final String ERROR_MSG = "Error attempting to launch web browser";

    /**
     * Opens the specified web page in the user's default browser
     *
     * @param url A web address (URL) of a web page (ex: "http://www.google.com/")
     */
    public static void openURL(String url) {
        String osName = System.getProperty("os.name");
        try {
            if (osName.startsWith("Mac OS")) {
                Class.forName("com.apple.eio.FileManager").getDeclaredMethod(
                        "openURL", new Class[]{String.class}).invoke(null,
                        new Object[]{url});
            } else if (osName.startsWith("Windows"))
                Runtime.getRuntime().exec(
                        "rundll32 url.dll,FileProtocolHandler " + url);
            else { //assume Unix or Linux
                boolean found = false;
                for (int i = 0; i < SUPPORTED_BROWSERS.length; i++)
                    if (!found) {
                        found = Runtime.getRuntime().exec(
                                new String[]{"which", SUPPORTED_BROWSERS[i]}).waitFor() == 0;
                        if (found)
                            Runtime.getRuntime().exec(new String[]{SUPPORTED_BROWSERS[i], url});
                    }
                if (!found) {
                    throw new Exception("Unsupported browser");
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, ERROR_MSG + "\n" + e.toString());
        }

    }

}
